



//父组件
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
///一般用于跨组件访问状态
class ParentGolablWidget extends  StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new ParentGolablWidgetState();
  }
}
GlobalKey<SubWidgetAState> subAkey = GlobalKey();
GlobalKey<SubWidgetBState> subBkey = GlobalKey();
class ParentGolablWidgetState extends State<ParentGolablWidget>{



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('组件化'),
      ),
      body: Center(
        child: Container(
          color: Colors.grey,
          width: 200,
          height: 200,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              SubWidgetA(key: subAkey),
              SubWidgetB(key: subBkey),
            ],
          ),
        ),
      ),
    );
  }

}


class SubWidgetA extends StatefulWidget{

  SubWidgetA({Key? key}):super(key: key);

  @override
  State<StatefulWidget> createState() {
    return SubWidgetAState();
  }


}

class SubWidgetAState extends State<SubWidgetA>{

  Color _backgroundColors = Colors.red;//红色
  void updateBackGroundColors(Color colos){
    setState(() {
      _backgroundColors = colos;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: (){
        subBkey.currentState?.updateBackGroundColors(Colors.blue);
        setState(() {
          _backgroundColors = Colors.red;
        });
      },
      child: new Container(
        width: 80,
        height: 80,
        color: _backgroundColors,
        alignment: Alignment.center,
        child: Text('subWidgetA'),
      ),
    );
  }
}

//子组件B
class SubWidgetB extends StatefulWidget {
  SubWidgetB({Key? key}):super(key:key);
  @override
  State<StatefulWidget> createState() {
    return new SubWidgetBState();
  }
}

class SubWidgetBState extends State<SubWidgetB>{

  Color _backgroundColors = Colors.green;//红色
  void updateBackGroundColors(Color colos){
    setState(() {
      _backgroundColors = colos;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: (){
        subAkey.currentState?.updateBackGroundColors(Colors.blue);
        setState(() {
          _backgroundColors = Colors.green;
        });
      },
      child: new Container(
        width: 80,
        height: 80,
        color: _backgroundColors,
        alignment: Alignment.center,
        child: Text('subWidgetB'),
      ),
    );
  }
}
